package com.yuanbao.filter;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yuanbao.base.enums.ResponseCodeEnum;
import com.yuanbao.base.response.Message;
import com.yuanbao.domain.PlatformUserLogin;
import com.yuanbao.domain.PublicInterface;
import com.yuanbao.mapper.PlatformUserLoginMapper;
import com.yuanbao.mapper.PublicInterfaceMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class TokenValidateFilter implements GlobalFilter, Ordered {
    @Autowired
    private PublicInterfaceMapper publicInterfaceMapper;

    @Autowired
    private PlatformUserLoginMapper platformUserLoginMapper;

    private boolean isPublicInterface(String path) {
        log.info("http request uri:{}", path);
        QueryWrapper<PublicInterface> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);
        List<String> uriList = publicInterfaceMapper.selectList(queryWrapper)
                .stream().map(PublicInterface::getUriStr).collect(Collectors.toList());
        return uriList.contains(path);
    }

    private String getTokenFromRequest(ServerHttpRequest request) {
        HttpHeaders headers = request.getHeaders();
        return headers.getFirst("accessToken");
    }

    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String message) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

        Message<String> errorMessage = new Message<>(ResponseCodeEnum.FORBIDDEN.getCode(), message);
        String json = JSONObject.toJSONString(errorMessage);

        DataBuffer buffer = response.bufferFactory().wrap(json.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(buffer));
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();

        if (isPublicInterface(path)) {
            return chain.filter(exchange);
        }

        String token = getTokenFromRequest(request);
        if (StringUtils.isBlank(token)) {
            return unauthorizedResponse(exchange, "请先登录");
        }

        if (!isValidToken(token)) {
            return unauthorizedResponse(exchange, "登录已过期，请重新登录");
        }

        return chain.filter(exchange);
    }

    private boolean isValidToken(String token) {
        QueryWrapper<PlatformUserLogin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("token", token);
        queryWrapper.eq("deleted", 0);
        queryWrapper.gt("token_expired_time", LocalDateTime.now());
        PlatformUserLogin loginRecord = platformUserLoginMapper.selectOne(queryWrapper);

        return loginRecord != null;
    }

    @Override
    public int getOrder() {
        return -100;
    }
}